﻿using System;

using lesson6; // 引用主项目中定义的类所在的命名空间

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class OrderServiceTests
{
    private OrderService service;
    private Order testOrder;

    [TestInitialize]
    public void Setup()
    {
        service = new OrderService();
        testOrder = new Order
        {
            OrderId = 1,
            Customer = new Customer { Name = "Test" },
            Details = new List<OrderDetails>
            {
                new OrderDetails { Product = new Product { Name = "Test", Price = 10 }, Quantity = 1 }
            }
        };
    }

    [TestMethod]
    public void AddOrder_ShouldAddNewOrder()
    {
        service.AddOrder(testOrder);
        Assert.AreEqual(1, service.QueryOrders(o => true).Count);
    }

    [TestMethod]
    [ExpectedException(typeof(Exception))]
    public void AddOrder_ShouldThrowWhenDuplicate()
    {
        service.AddOrder(testOrder);
        service.AddOrder(testOrder);
    }

    [TestMethod]
    public void DeleteOrder_ShouldRemoveOrder()
    {
        service.AddOrder(testOrder);
        service.DeleteOrder(1);
        Assert.AreEqual(0, service.QueryOrders(o => true).Count);
    }

    [TestMethod]
    [ExpectedException(typeof(Exception))]
    public void DeleteOrder_ShouldThrowWhenNotFound()
    {
        service.DeleteOrder(999);
    }

    [TestMethod]
    public void ModifyOrder_ShouldUpdateOrder()
    {
        service.AddOrder(testOrder);
        var newOrder = new Order { OrderId = 1, Customer = new Customer { Name = "Modified" } };
        service.ModifyOrder(1, newOrder);
        Assert.AreEqual("Modified", service.QueryOrders(o => true)[0].Customer.Name);
    }

    [TestMethod]
    public void QueryOrders_ShouldReturnFilteredResults()
    {
        service.AddOrder(testOrder);
        var results = service.QueryOrders(o => o.OrderId == 1);
        Assert.AreEqual(1, results.Count);
    }

    [TestMethod]
    public void SortOrders_ShouldSortByKeySelector()
    {
        var order2 = new Order { OrderId = 2, Customer = new Customer { Name = "Test" } };
        service.AddOrder(order2);
        service.AddOrder(testOrder);

        service.SortOrders(o => o.OrderId);
        var orders = service.QueryOrders(o => true);
        Assert.AreEqual(1, orders[0].OrderId);
    }

    [TestMethod]
    public void ExportImport_ShouldPreserveData()
    {
        service.AddOrder(testOrder);
        string tempFile = Path.GetTempFileName();

        service.ExportToXml(tempFile);
        var newService = new OrderService();
        newService.ImportFromXml(tempFile);

        Assert.AreEqual(1, newService.QueryOrders(o => true).Count);
        File.Delete(tempFile);
    }
}